package com.example.first.adapters;



import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.first.R;
import com.example.first.modle.ApiResponse;
import com.example.first.modle.CartItem;
import com.example.first.modle.ShoppingCart;
import com.example.first.services.ApiService;
import com.example.first.utils.RetrofitClient;

import org.w3c.dom.Text;

import java.math.BigDecimal;
import java.util.List;

import retrofit2.Call;

public class CartAdapter extends BaseAdapter {
    private Context context;
    private List<CartItem> cartItems;

    private Activity parentActivity;
    private Dialog dialog;

    public CartAdapter(Context context, List<CartItem> cartItems, Dialog dialog,Activity activity) {
        this.context = context;
        this.cartItems = cartItems;
        this.parentActivity=activity;
        this.dialog=dialog;
    }


    @Override
    public int getCount() {
        // 添加空值检查
        return cartItems != null ? cartItems.size() : 0;
    }

    @Override
    public Object getItem(int i) {
        return cartItems != null ? cartItems.get(i) : null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        CartAdapter.ViewHolder viewHolder;

        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.cart_item_layout, parent, false);
            viewHolder = new CartAdapter.ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (CartAdapter.ViewHolder) convertView.getTag();
        }

        if (cartItems != null && position < cartItems.size()) {
            CartItem cartItem = cartItems.get(position);
            viewHolder.nameText.setText(cartItem.getName());
            viewHolder.priceText.setText(String.valueOf(cartItem.getAmount()));
            viewHolder.numberText.setText(String.valueOf(cartItem.getNumber()));

            if(cartItem.getDishFlavor()!=null){
                viewHolder.dishFlavor.setText(cartItem.getDishFlavor());

            }


            // 使用Glide加载图片
            Glide.with(context)
                    .load(cartItem.getImage())
                    .into(viewHolder.imageView);
        }

        //设置按钮的点击事件
        viewHolder.subButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                ShoppingCart shoppingCart=new ShoppingCart();
                shoppingCart.setDishId(cartItems.get(position).getDishId());
                ApiService apiService=RetrofitClient.getApiService();
                Call<ApiResponse<String>> call=apiService.subCart(shoppingCart);
                call.enqueue(new retrofit2.Callback<ApiResponse<String>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<String>> call, retrofit2.Response<ApiResponse<String>> response) {
                        if(response.isSuccessful() && response.body()!=null){
                            if(response.body().getCode()==1){
                                // 减前端显示数量
                                int number=cartItems.get(position).getNumber();
                                if(number>1){
                                    cartItems.get(position).setNumber(number-1);
                                }else {
                                    cartItems.remove(position);
                                }
                                // 计算总金额并显示
                                if (!cartItems.isEmpty()) {
                                    BigDecimal amounts = BigDecimal.ZERO;
                                    for (CartItem cartItem : cartItems) {
                                        BigDecimal amount = cartItem.getAmount();
                                        BigDecimal number1 = new BigDecimal(cartItem.getNumber());
                                        amounts = amounts.add(amount.multiply(number1));
                                    }
                                    TextView viewById = dialog.findViewById(R.id.text_view);
                                    viewById.setText("￥" + amounts.toString());
                                    //修改mainFloat金额
                                    TextView m_view = parentActivity.findViewById(R.id.text_view);
                                    m_view.setText("￥" + amounts.toString());
                                }else {
                                    TextView viewById = dialog.findViewById(R.id.text_view);
                                    viewById.setText("￥" +"0");
                                    //修改mainFloat金额
                                    TextView m_view = parentActivity.findViewById(R.id.text_view);
                                    m_view.setText("￥" + "0");
                                }

                                notifyDataSetChanged();



                            }else {
                                Toast.makeText(context, response.body().getMsg(), Toast.LENGTH_SHORT);
                            }
                        }
                    }
                    @Override
                    public void onFailure(Call<ApiResponse<String>> call, Throwable t) {
                        //处理失败情况
                        Toast.makeText(context, "请求失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        viewHolder.addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ShoppingCart shoppingCart=new ShoppingCart();
                shoppingCart.setDishId(cartItems.get(position).getDishId());
                ApiService apiService=RetrofitClient.getApiService();
                Call<ApiResponse<String>> call=apiService.addCart(shoppingCart);
                call.enqueue(new retrofit2.Callback<ApiResponse<String>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<String>> call, retrofit2.Response<ApiResponse<String>> response) {
                        if(response.isSuccessful()&&response.body()!=null){
                            if(response.body().getCode()==1){
                                cartItems.get(position).setNumber(cartItems.get(position).getNumber()+1);


                                // 计算总金额并显示
                                if (!cartItems.isEmpty()) {
                                    BigDecimal amounts = BigDecimal.ZERO;
                                    for (CartItem cartItem : cartItems) {
                                        BigDecimal amount = cartItem.getAmount();
                                        BigDecimal number = new BigDecimal(cartItem.getNumber());
                                        amounts = amounts.add(amount.multiply(number));
                                    }
                                    TextView viewById = dialog.findViewById(R.id.text_view);
                                    viewById.setText("￥" + amounts.toString());
                                    //修改mainFloat金额
                                    TextView m_view = parentActivity.findViewById(R.id.text_view);
                                    m_view.setText("￥" + amounts.toString());
                                }else {
                                    TextView viewById = dialog.findViewById(R.id.text_view);
                                    viewById.setText("￥" +"0");
                                    //修改mainFloat金额
                                    TextView m_view = parentActivity.findViewById(R.id.text_view);
                                    m_view.setText("￥" + "0");
                                }




                                notifyDataSetChanged();


                            }else {
                                Toast.makeText(context, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    @Override
                    public void onFailure(Call<ApiResponse<String>> call, Throwable t) {
                        //处理失败情况
                        Toast.makeText(context, "请求失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        return convertView;
    }

    public void setCartItems(List<CartItem> cartItems) {
        this.cartItems = cartItems;
        notifyDataSetChanged();
    }

    static class ViewHolder {
        TextView nameText;
        ImageView imageView;
        TextView numberText;
        TextView priceText;
        ImageButton addButton;
        ImageView subButton;
        TextView totalPriceText;
        TextView dishFlavor;

        ViewHolder(View view) {
            nameText = view.findViewById(R.id.cart_dish_name_text_view);
            imageView = view.findViewById(R.id.cart_dish_image_view);
            numberText = view.findViewById(R.id.quantityTextView);
            priceText = view.findViewById(R.id.cart_dish_price_text_view);
            subButton= view.findViewById(R.id.decreaseQuantityButton);
            addButton=view.findViewById(R.id.increaseQuantityButton);
            totalPriceText=view.findViewById(R.id.text_view);
            dishFlavor=view.findViewById(R.id.dish_flavor);
        }
    }
}

